﻿using System.Web.Mvc;
using FShare.DataModel;
using System.Linq;
using FShare.ViewModels;
using System.Collections.Generic;
using System.Web.Security;
using FShare.Helpers;

namespace FShare.Controllers
{
    [Authorize(Roles = "FShareAdmin")]
    public class AdministratorController : Controller
    {
        //
        // GET: /Administrator/

        public ActionResult Index()
        {
            return RedirectToAction("Users");
        }

        /// <summary>
        /// Gives a list of uploaded files
        /// </summary>
        /// <param name="id">Search criteria</param>
        /// <returns></returns>
        public ActionResult FileManagement(string id)
        {
            var model = GetListOfFiles(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult FileManagement()
        {
            var model = GetListOfFiles(null);
            if (Request.Params["searchbox"] != null)
            {
                model = GetListOfFiles(Request.Params["searchbox"]);
            }
            return View(model);
        }

        private List<UploadedFileViewModel> GetListOfFiles(string criteria)
        {
            var model = new List<UploadedFileViewModel>();
            using (var context = new FShareDataModelContainer())
            {
                IEnumerable<FShareFile> files = null;
                if (string.IsNullOrEmpty(criteria))
                {
                    files = context.FShareFiles
                        .Where(f => !f.IsDeleted)
                        .OrderByDescending(f => f.DateUploaded)
                        .AsEnumerable();
                }
                else
                {
                    files = context.FShareFiles
                        .Where(f => !f.IsDeleted
                            && (f.Name.Contains(criteria)
                            || f.Description.Contains(criteria)
                            || f.DownloadSecret == criteria
                            || f.DeleteSecret == criteria
                            || f.GroupKey == criteria
                            || f.DestinationEmail == criteria
                            || f.Uploader.UserName == criteria))
                            .OrderByDescending(f => f.DateUploaded)
                            .AsEnumerable();
                }

                foreach (var file in files)
                {
                    var item = new UploadedFileViewModel
                    {
                        DeleteSecret = file.DeleteSecret,
                        Description = file.Description,
                        DownloadSecret = file.DownloadSecret,
                        FileName = file.Name,
                        NumberOfDownloads = file.NumberOfDownloads,
                        UploadedTime = file.DateUploaded,
                    };
                    User uploader = null;
                    if (file.UploaderGuid.HasValue)
                    {
                        uploader = context.UserSet.Where(u => u.UserId == file.UploaderGuid.Value).FirstOrDefault();
                    }

                    item.UploaderUserName = uploader == null ? string.Empty : uploader.UserName;
                    model.Add(item);
                }
            }

            return model;
        }

        /// <summary>
        /// Lists all users
        /// </summary>
        /// <returns></returns>
        public ActionResult Users()
        {
            var model = new List<UsersViewModel>();
            using (var context = new FShareDataModelContainer())
            {
                string currentUser = User.Identity.Name;
                var users = context.UserSet.Include("FShareFiles")
                    .Where(u => u.UserName != currentUser).AsEnumerable();

                foreach (var user in users)
                {
                    var item = new UsersViewModel
                    {
                        UserName = user.UserName,
                        EMail = Membership.GetUser(user.UserName).Email,
                        IsAdministrator = Roles.IsUserInRole(user.UserName, RoleConstants.ROLE_ADMIN),
                        LastActivity = user.LastActivityDate,
                        UploadedFilesCount = user.FShareFiles.Count
                    };

                    model.Add(item);
                }
            }
            return View(model);
        }

        /// <summary>
        /// Changes the role of the given user
        /// </summary>
        /// <param name="id">the usernam</param>
        /// <returns></returns>
        public ActionResult ChangeRole(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var roles = Roles.GetRolesForUser(id);
                if (roles != null)
                {
                    if (roles.Length > 0 && roles[0] == RoleConstants.ROLE_ADMIN)
                    {
                        Roles.RemoveUserFromRole(id, RoleConstants.ROLE_ADMIN);
                        Roles.AddUserToRole(id, RoleConstants.ROLE_BASIC_USER);
                    }
                    else
                    {
                        Roles.RemoveUserFromRole(id, RoleConstants.ROLE_BASIC_USER);
                        Roles.AddUserToRole(id, RoleConstants.ROLE_ADMIN);
                    }
                }
            }

            return RedirectToAction("Users");
        }
    }
}
